import {
  isAndroid,
  isIOS,
  isTencentWebview,
  getQueryParamByName,
  getBrowserType,
  BROWSER,
  DomUtil,
  catchGlobalError,
  uploadErrorInfo,
  onloadImage,
  getCacheUUID,
  fileUrlHandled,
  isNeedWebClip,
  isNeedKeFuWebClip,
  getEnTitleName,
  isAppUpdate,
} from '@/common/js/common';
import ua2obj from 'ua2obj';
import { Base64 } from 'js-base64';
import * as qs from 'qs';
import queryString from 'query-string';
import ClipboardJS from 'clipboard';
import '@/common/phpFile/css/ba.css';
import '../style/mobile_ky.scss';
import '../style/animate.css';
import request from '../js/request';
import ProgressBar from 'progressbar.js';
import { nameConfig } from '@theme/vm';
import $ from 'jquery';
const SITE_NAME = process.env.SITE_NAME || '';
const imgPath = SITE_NAME + '_appdown';
const defWebClipUrl = '/api/findmed/v2/member/webclip/download';
let webClipPreUrl = defWebClipUrl;
// 这里的桌面客服的下载地址是  当前域名 + defKefuWebClipUrl 再 拼接 ?url=xxx, xxx 是 preInfo接口的 _webclip_book_mark
const defKefuWebClipApi = '/api/findmed/v2/member/webclip/customer/download';
const ModalType = {
  iosNoSafari: 'iosNoSafari',
  ios: 'ios',
  android: 'android',
};

catchGlobalError();

export default function (appKey: string, type: 'sport' | 'site') {
  const isSport = type === 'sport';
  const i_code: any = getQueryParamByName('i_code');
  const r_code = getQueryParamByName('r_code');
  let isCustomer = getQueryParamByName('isCustomer');
  let app_android_download = '';
  let app_ios_download = '';
  const ios_download = nameConfig.ios_download; // ios线上包地址
  const android_download = nameConfig.android_download; // 安卓线上包地址
  let android_webclip_book_mark = ''; // 安卓客服webclip书签
  let ios_webclip_book_mark = ''; // ios客服 webclip书签

  let h5_domain = nameConfig.h5_domain;
  let locationIp = '';
  let ipAddress = '';
  let isCustomerClick = false;
  let customer_domain = '';

  try {
    // 设置网页标题，这样做避免微信封杀
    if (i_code) {
      document.title =
        Base64.decode(`${nameConfig.welComeText}`) +
        getEnTitleName(nameConfig?.brand) +
        Base64.decode(`${nameConfig.brandName}QXBw`) +
        i_code;
    } else if (r_code) {
      document.title =
        Base64.decode(`${nameConfig.welComeText}`) +
        getEnTitleName(nameConfig?.brand) +
        Base64.decode(`${nameConfig.brandName}QXBw`) +
        r_code;
    } else {
      document.title =
        Base64.decode(`${nameConfig.welComeText}`) +
        getEnTitleName(nameConfig?.brand) +
        Base64.decode(`${nameConfig.brandName}`);
      // 取消QXBw 标题显示了个 欢迎使用69娱乐\
      console.log(
        Base64.decode(`${nameConfig.welComeText}`) +
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`${nameConfig.brandName}QXBw`)
      );
    }
  } catch (error) {
    uploadErrorInfo('game.setTitle', error, false);
  }

  try {
    // 如果是非移动端用户
    if (!isIOS() && !isAndroid()) {
      let subfix = '';

      if (i_code) {
        subfix = '?i_code=' + i_code;
      } else if (r_code) {
        subfix = '?r_code=' + r_code;
      }
      // 跳转至PC端页面
      if (isSport) {
        // window.location.href = 'downloadty_com.html' + subfix;
        window.location.href = 'download.html' + subfix;
      } else {
        // window.location.href = 'download_com.html' + subfix;
        window.location.href = 'download.html' + subfix;
      }
      // window.location.href = 'download.html' + subfix;
      return;
    }
  } catch (error) {
    uploadErrorInfo('game.forward', error, false);
    return;
  }

  // 初始化 webClip 相关
  function initWebClip() {
    try {
      const fdqInstallBtn = document.querySelector<HTMLElement>('#fdqInstall');
      const isSafari = getBrowserType() === BROWSER.SAFARI;
      const modalType = isSafari
        ? ModalType.ios
        : isIOS()
        ? ModalType.iosNoSafari
        : ModalType.android;
      updateModalContent(modalType);
      if (fdqInstallBtn) {
        fdqInstallBtn.addEventListener('click', () => {
          isCustomer = '';
          isCustomerClick = false;
          updateModalContent(type);
          toAppPostTycm();
          webClipPreUrl = defWebClipUrl;
          setTimeout(() => {
            // 如果是 IOS safari 点击先下载再弹框
            if (modalType === ModalType.ios) {
              modalBtnClick(modalType);
            }
            showModal(modalType);
          }, 500);
        });
      }
    } catch (error) {
      uploadErrorInfo('game.installBtn.click', error, false);
    }
  }

  // 初始化 客服 webClip 相关
  function initCustomerWebClip() {
    try {
      const isSafari = getBrowserType() === BROWSER.SAFARI;
      const modalType = isSafari
        ? ModalType.ios
        : isIOS()
        ? ModalType.iosNoSafari
        : ModalType.android;
      updateModalContent(modalType);

      // 如果是从 h5/app 跳转过来的直接弹框
      if (isCustomer === '1') {
        const webclipBookMark = isIOS()
          ? ios_webclip_book_mark
          : android_webclip_book_mark;
        webClipPreUrl = defKefuWebClipApi + '?url=' + webclipBookMark;
        showModal(modalType);
      }
    } catch (error) {
      console.log('---------初始化 客服 webclip 相关失败----------', error);
    }
  }

  function initTySCM() {
    try {
      const downloadPanel = document.querySelector<HTMLElement>('#download');
      if (downloadPanel) {
        DomUtil.show(downloadPanel);
        // 处理下载webclip逻辑
        if (isNeedWebClip() && isIOS()) {
          initWebClip();
        }
      }
    } catch (error) {
      uploadErrorInfo('game.initTySCM', error, false);
    }
  }

  // 下载上报
  const toAppPostTycm = () => {
    const clipboardInfo = clipboardInfos();
    const data = JSON.stringify({
      ...clipboardInfo,
      startDownloadTime: parseInt(String(new Date().getTime() / 1000), 0),
    });
    const sendData = {
      data,
      uidMap: {
        deviceUid: getCacheUUID(),
        deviceUid_ip: `${getCacheUUID()}_${locationIp || ''}`,
      },
    };
    request({
      url: '/jbinstall/v1/submitInfo',
      params: sendData,
      callback: (res: any) => {
        if (res.code === 6000) {
          //
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
      method: 'post',
    });
  };

  function showAppUpdateTips() {
    if (isAppUpdate()) {
      const confirmModal = document.getElementById('confirmModal');
      const modalOverlayTips = document.getElementById('modalOverlayTips');
      if (confirmModal && modalOverlayTips) {
        document.getElementById('confirmModal').style.display = 'block';
        document.getElementById('modalOverlayTips').style.display = 'block';
      }
      const confirmButton = document.getElementById('confirmButton');
      if (confirmButton) {
        confirmButton.addEventListener('click', function () {
          document.getElementById('confirmModal').style.display = 'none';
          document.getElementById('modalOverlayTips').style.display = 'none';
        });
      }
    }
  }

  // 请求前置信息
  function initGetInfo() {
    request({
      url: '/api/findmed/v2/member/preInfo',
      method: 'post',
      params: {},
      callback: (res: any) => {
        if (res.status) {
          const resData = res?.data;
          app_ios_download =
            resData?.site_domain?.app_ios_download || ios_download;
          app_android_download =
            resData?.site_domain?.app_android_download || android_download;
          // 客服 webclip 书签地址
          android_webclip_book_mark =
            resData?.site_domain?.android_webclip_book_mark || '';
          ios_webclip_book_mark =
            resData?.site_domain?.ios_webclip_book_mark || '';

          if (resData?.customer_service) {
            document
              .querySelector<HTMLElement>('.customer_service')
              .addEventListener('click', function (e) {
                e.preventDefault();
                window.location.href = resData?.customer_service;
              });
          }
          // 这里循环判断返回的下载地址是否包含i_code或r_code，如果有就替换原来的下载地址
          const h5_navigation_domain =
            res?.data?.site_domain?.h5_navigation_domain;
          const domainArr = h5_navigation_domain.split(',');
          const urlParams = i_code ? '?i_code=' + i_code : '';

          const urlData = [];
          domainArr.forEach((item, index) => {
            if (index < 3) urlData.push(item + urlParams);
          });

          let html = '';
          for (let i = 0; i < 3; i++) {
            const url = urlData[i] ? urlData[i] : urlData[0];
            html += `<a href="${url}" class="domain-item" target="_blank">
                        <div class="time_text">12ms</div>
                        <div class="text" style="overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;margin-left:10px;width:200px">${url}</div>
                      </a>`;
          }
          const speedList = document.querySelector<HTMLElement>('#domainList');
          speedList.innerHTML = html;

          if (res?.data?.site_domain?.h5_domain) {
            h5_domain = res?.data?.site_domain?.h5_domain.trim();
          }
          if (
            resData &&
            ((ios_webclip_book_mark && isIOS()) ||
              (android_webclip_book_mark && isAndroid()))
          ) {
            if (isNeedKeFuWebClip()) {
              const serviceCard =
                document.querySelector<HTMLElement>('#serviceCard');
              if (serviceCard) {
                serviceCard.style.display = 'block';
              }
              if (resData?.site_domain?.app_game_download_domain) {
                customer_domain =
                  resData?.site_domain?.app_game_download_domain?.trim() +
                  '/customer.html';
              }

              // customer_domain
              initCustomerWebClip();
            }
          }
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
    });

    request({
      url: '/api/findmed/v2/jbinstall/ip/location',
      method: 'post',
      params: {},
      callback: (res: any) => {
        if (res.code === 6000) {
          locationIp = res?.data?.ip;
          const location = res?.data?.location;
          if (location) {
            const ipAddressArr = [
              locationIp,
              location.Country,
              location.Province,
              location.City,
            ];
            ipAddress = JSON.stringify(ipAddressArr);
          }
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
    });
  }

  function preloadImage() {
    // 全站图片列表
    const contentList = [
      {
        imgurl: `/resource_images/${imgPath}/download_v2/fullsite_content_page3.jpg?__static_hash__`,
      },
    ];

    onloadImage(contentList);
  }

  //
  function initVerticalBtns() {
    const installVb = document.querySelector<HTMLElement>('#installVb');
    if (installVb) {
      installVb.addEventListener('click', function () {
        normalInstallFunc();
      });
    }

    const installVb1 = document.querySelector<HTMLElement>('#installVb1');
    if (installVb1) {
      installVb1.addEventListener('click', function () {
        normalInstallFunc();
      });
    }
  }

  initCopy();
  initGetInfo();
  initTySCM();
  showICode();
  preloadImage();
  initOther();
  initReport();
  initVerticalBtns();
  showAppUpdateTips();
  initEvent();

  return isTencentWebview() ? displayViewGuide() : '';

  // app普通下载事件
  function normalInstallFunc() {
    // 清除桌面客服文字
    isCustomer = '';
    isCustomerClick = false;
    updateModalContent(type);
    try {
      toAppPostTycm();
      setTimeout(() => {
        if (isIOS()) {
          fileUrlHandled(app_ios_download);
        } else {
          window.location.href = app_android_download;
        }
      }, 200);
    } catch (error) {
      uploadErrorInfo('game.installBtn.click', error, false);
    }
  }

  function initCopy() {
    // 需要写入剪切板：appKey，设备参数，自定义参数
    const clipboardInfo = clipboardInfos();
    new ClipboardJS('body', {
      text: () => {
        // 写入剪切板的格式：json字符串
        return Base64.encode(JSON.stringify(clipboardInfo));
      },
    });
  }

  /**
   * 第一次上报信息
   *
   */
  function initReport() {
    setTimeout(function () {
      // 刚进来页面时执行第一次日志上报
      const deviceInfo: any = ua2obj();
      if (ipAddress) {
        deviceInfo.ipAddress = ipAddress;
      }
      const query = queryString.parse(window.location.search || '');
      const params = {
        uuid: getCacheUUID(),
        client_type: 'h5',
        device: JSON.stringify(deviceInfo),
        value: JSON.stringify(query),
      };
      request({
        url: '/api/findmed/v2/jbinstall/addAppInfo',
        method: 'post',
        params,
        callback: (res: any) => {
          //
        },
        fail: (err: any) => {
          console.log(err);
        },
      });
    }, 1000);
  }

  /**
   * displayViewGuide 引导
   */
  function displayViewGuide() {
    try {
      const tmpl =
        '<div class="app-guide-mask"><div class="blur"></div><span class="guide-img"></span></div>';

      const appGuideMask = DomUtil.create(tmpl);

      if (appGuideMask) {
        document.body.appendChild(appGuideMask);

        appGuideMask.addEventListener('touchmove', function (event: Event) {
          event.preventDefault();
        });

        appGuideMask.addEventListener('click', function () {
          DomUtil.remove(appGuideMask);
        });
      }
    } catch (error) {
      uploadErrorInfo('game.displayViewGuide', error, false);
    }
  }

  // ----------------  webclicp ----------------------
  // 更新模态框内容  type1: IOS非safari浏览器  type2: IOS 未安装描述文件 type3 安卓下载
  // tslint:disable-next-line:no-shadowed-variable
  function updateModalContent(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const homeUrl = isCustomerClick
      ? `${h5_domain} ${subfix}`
      : customer_domain;
    // 模态框内容配置
    const modalContents = {
      iosNoSafari: {
        imageUrl: `/resource_images/${imgPath}/common/icon_safari.${
          window.supportWebp ? 'webp' : 'png'
        }?__static_hash__`,
        title: '使用safari浏览器',
        description: '防掉签需要使用safrai下载描 述文件并进行安装。',
        buttonText: '复制域名',
      },
      ios: {
        imageUrl: `/resource_images/${imgPath}/common/icon_seting.${
          window.supportWebp ? 'webp' : 'png'
        }?__static_hash__`,
        title: `${
          isCustomer === '2' || isCustomer === '1' ? '桌面客服' : ''
        }安装描述文件`,
        description: '在设置>通用>VPN与设备管理 可见描述文件。',
        buttonText: isCustomer === '1' ? '桌面客服下载' : '重新下载',
      },
      android: {
        imageUrl: '',
        title: '下载到桌面?[如已下载请忽略]',
        description: `如无法正常下载到桌面,请下载【最新版本的Google浏览器】，打开Google浏览器，输入本站网址 ${homeUrl}，点击右上角的【菜单】然后选择【下载到桌面】即可完成WEB版APP`,
        buttonText: '下载到桌面',
      },
    };
    const content = modalContents[type];
    if (content) {
      if (type === ModalType.android) {
        $('#modal img').css('display', 'none');
        $('#modal .modal-title').css('margin-top', '45px');
        $('#modal .modal-title').css('font-size', '20px');
        $('#modal .modal-description').css('font-size', '15px');
      } else {
        $('#modal img').attr('src', content.imageUrl);
      }
      $('#modal .modal-title').text(content.title);
      $('#modal .modal-description').text(content.description);
      $('#modal .modal-button').text(content.buttonText);
    }
  }

  // tslint:disable-next-line:no-shadowed-variable
  function showModal(type: string) {
    $('#modal-overlay').css('visibility', 'visible');
    $('#modal').css('visibility', 'visible');
    // 显示模态框
    $('#modal-overlay').fadeIn();

    // 关闭模态框
    $('#modal-overlay').click(() => {
      $('#modal-overlay').fadeOut();
    });

    // 关闭模态框 对应弹框 下载/复制按钮事件
    $('#modalButton').click(() => {
      modalBtnClick(type);
      $('#modal-overlay').fadeOut();
    });

    // 阻止modal内部点击事件冒泡
    $('#modal').click((event: Event) => {
      event.stopPropagation();
    });
  }

  function doPromptEvent() {
    const win: any = window;
    if (win.savedPrompt) {
      const promptEvent = win.savedPrompt as any; // 类型断言，因为我们知道 savedPrompt 是什么
      promptEvent.prompt();
      // 等待用户做出响应
      promptEvent.userChoice.then((choiceResult: any) => {
        if (choiceResult.outcome === 'accepted') {
          console.log('用户接受了安装应用');
        } else {
          console.log('用户拒绝了安装应用');
        }
        win.savedPrompt = null;
      });
    }
  }
  function modalBtnClick(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = `${webClipPreUrl}${subfix}`;
    console.log('不再是standalone模式', window);
    if (type === ModalType.iosNoSafari) {
      initCopyWebClip();
    } else {
      if (type === ModalType.android) {
        doPromptEvent();
      } else {
        // 下载 webclip
        fileUrlHandled(webclipUrl);
      }
    }
  }

  function initCopyWebClip() {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = `${webClipPreUrl}${subfix}`;

    navigator.clipboard
      .writeText(webclipUrl)
      .then(() => {
        alert('复制成功');
      })
      .catch(() => {
        alert('复制失败');
      });
  }

  // ----------------  webclicp ----------------------
  /**
   * 初始化一些其它的东西
   * 安装引导图、样式微调、IOS额外添加一键信任相关按钮、弹框
   */
  function initOther() {
    try {
      window.supportWebp =
        document
          .createElement('canvas')
          .toDataURL('image/webp')
          .indexOf('data:image/webp') === 0
          ? true
          : false;
    } catch (err) {
      window.supportWebp = false;
    }
    try {
      const remind = document.querySelector<HTMLElement>('.remind');
      if (isAndroid()) {
        if (remind) {
          remind.classList.add('android');
          remind.style.minHeight = '100%';
        }
      } else {
        if (remind) {
          remind.classList.remove('android');
        }
      }

      // 安装教程
      $('#tutorial').click(() => {
        console.log(1234);
        $('#tutorialModal').css('visibility', 'visible');
        // 显示模态框
        $('#tutorialModal').fadeIn();
      });
      // 关闭模态框
      $('#tutorialModal').click(() => {
        $('#tutorialModal').fadeOut();
      });
    } catch (error) {
      uploadErrorInfo('game.initOther', error, false);
    }
  }

  function getProgressBarColo(brand: string) {
    const res = {
      color: '#ceb89f',
      trailColor: '#e6e1dc',
    };
    switch (brand) {
      case 'ky':
        res.color = '#CCC088';
        res.trailColor = '#CCC088';
        break;
      default:
        break;
    }
    return res;
  }

  /**
   * 下载开始假的进度条
   *
   */
  function downloadProgress() {
    const installBtn = document.querySelector<HTMLElement>('#install');
    const trustElem = document.querySelector<HTMLElement>('#trust');
    const progress = document.querySelector<HTMLElement>('#progress');
    const progressContainer =
      document.querySelector<HTMLElement>('#progressContainer');
    let timer;
    let i = 30;
    const bar = new ProgressBar.Circle(progress, {
      strokeWidth: 5,
      easing: 'linear',
      duration: 1500,
      color: getProgressBarColo(nameConfig.brand).color,
      trailColor: getProgressBarColo(nameConfig.brand).trailColor,
      trailWidth: 5,
      svgStyle: null,
      step: (state, circle) => {
        const value = Math.round(circle.value() * 100);
        circle.setText(value + '%');
      },
    });
    // 下载时隐藏下载完成按钮 显示进度条及信任按钮
    if (installBtn && progressContainer) {
      installBtn.style.display = 'none';
      progressContainer.style.display = 'flex';
    }
    // 如果是安卓显示正在下载
    if (isAndroid()) {
      (trustElem as any).innerText = nameConfig.nowText + '...';
    }
    clearInterval(timer);
    timer = setInterval(() => {
      task();
    }, 1000);

    function task() {
      try {
        if (i <= 0) {
          bar.animate(1);
          setTimeout(() => {
            downloadComplete();
          }, 1500);
          clearInterval(timer);
          timer = null;
        } else {
          i--;

          if (Math.random() > 0.3 && installBtn) {
            const num = Math.floor(((30 - i) / 30) * 100);
            bar.animate(num / 100);
          }
        }
      } catch (error) {
        uploadErrorInfo('game.downloadProgress', error, false);
      }
    }
  }

  /**
   * IOS进度条读完后处理
   *
   */
  function downloadComplete() {
    try {
      const installBtn = document.querySelector<HTMLElement>('#install');
      const installDiv = document.querySelector<HTMLElement>('#installDiv');
      const confirmCompletedElem =
        document.querySelector<HTMLElement>('.confirm_completed');
      const trustElem = document.querySelector<HTMLElement>('#trust');

      if (installBtn && installDiv) {
        installBtn.setAttribute('disabled', 'disabled');
        installDiv.style.display = 'none';
        const Button: any = isAndroid() ? trustElem : installBtn;
        DomUtil.addClass(Button, 'install_end');
        Button.innerHTML = `<img src="/resource_images/${imgPath}/common/icon_dui.${
          window.supportWebp ? 'webp' : 'png'
        }?__static_hash__"><span>${nameConfig.successText}</span>`;
      }
      if (isIOS()) {
        if (confirmCompletedElem) {
          confirmCompletedElem.innerText =
            '请确认APP下载完成后，再点击“一键信任”';
        }
        if (trustElem) {
          DomUtil.addClass(trustElem, 'trust_active');
          trustElem.addEventListener('click', function () {
            window.location.href = `/resource_images/${imgPath}/common/open.mobileprovision`;
          });
          trustElem.removeAttribute('disabled');
        }
      }
    } catch (error) {
      uploadErrorInfo('game.downloadComplete', error, false);
    }
  }

  /**
   * 展示ICode
   *
   */
  function showICode() {
    try {
      if (i_code) {
        // 设置i_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = i_code === 'nobody' ? '' : i_code;
        }
      } else if (r_code) {
        // 设置r_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = r_code === 'nobody' ? '' : r_code;
        }
      }
    } catch (error) {
      uploadErrorInfo('game.showICode', error, false);
    }
  }
}

function initEvent() {
  setInterval(function () {
    setSign();
  }, 1500);
}

function setSign() {
  var signalDelayElement = document.querySelectorAll('.time_text');
  for (var i = 0; i < signalDelayElement.length; i++) {
    var tmpElement = signalDelayElement[i];
    var count = Math.random() * 5;

    if (count < 1) {
      var max = 10;
      var min = 6;
      var random = (Math.random() * (max - min) + min).toFixed(2) + 'ms';

      setInnerText(tmpElement, random);
    } else if (count > 3) {
      var random = Math.random().toFixed(2) + 'ms';
      setInnerText(tmpElement, random);
    } else {
      var max = 5;
      var min = 2;
      var random = (Math.random() * (max - min) + min).toFixed(2) + 'ms';
      setInnerText(tmpElement, random);
    }
  }
}

function setInnerText(element, text) {
  if (typeof element.textContent == 'string') {
    element.textContent = text;
  } else {
    element.innerText = text;
  }
}

// 剪贴板数据
function clipboardInfos(): any {
  // 提取url参数
  const urlParams = qs.parse(window.location.search, {
    ignoreQueryPrefix: true,
  });
  const platform = isIOS() ? 'ios' : 'android';
  // 需要写入剪切板：appKey，设备参数，自定义参数
  const clipboardInfo = Object.assign({
    data: urlParams,
    url: location.href,
    hasData: Object.keys(urlParams).length > 0 ? 1 : 0,
    screen: window.screen.width * window.screen.height, // 屏幕宽高得出的积
    platform, // 平台类型
  });

  return clipboardInfo;
}
